#include "stdafx.h"
#include "SessionCM.h"
#include "Message/MsgSession.h"
#include "Message/MsgEntity.h"

//
SessionCM::SessionCM(boost::asio::io_service &svcIO, Service* wpSvcL, Service* wpSvcH, IMsgBuilder* wpBuilder)
:Session(svcIO), m_wpLgcSvc(wpSvcL), m_wpHostSvc(wpSvcH), m_wpMsgBuilder(wpBuilder), m_bDying(false)
{
}


void
SessionCM::onInput(const boost::system::error_code& error, size_t bytes_transferred, MsgBuffer* buffer )
{
	//MsgGetEntityList* response = new MsgGetEntityList;
	//response->setSID(getID());
	//response->nAccountID = 20;
	//m_wpHostSvc->postMsg(response);
	//return;

	if (m_bDying)
	{
		LOG_DEBUG("Session is already closing!")
		return;
	}

	if(error || bytes_transferred==0)
	{
		m_bDying = true;
		LOG_DEBUG("Session is closing!");

		//
		//	notify network layer to close session
		IMsg* pMsg = new MsgSessionClosed(getID());
		m_wpHostSvc->postMsg(pMsg);
		return;
	}

	buffer->commit(bytes_transferred);

	MsgIStream stream(*buffer);
	IMsg* pMsg = NULL;

	if (m_wpMsgBuilder->onDecodeMsg(pMsg, stream) && pMsg!=NULL)
	{
		pMsg->setSID(getID());
		m_wpLgcSvc->postMsg(pMsg);
	}
	else
	{
		LOG_ERROR("Failed to decode network message!");
	}

	//
	//	try to read one more message
	//
	read();
}

bool
SessionCM::write(IMsg* pMsg)
{
	MsgBuffer* buffer = new MsgBuffer;
	MsgOStream stream(*buffer);
	if (m_wpMsgBuilder->onEncodeMsg(pMsg, stream))
	{
		Session::write(buffer);
	}
	else
	{
		pMsg->dump();
		LOG_ERROR("Failed to encode upper msg");
		delete buffer;
	}
	return true;
}


void
SessionCM::onOutput(const boost::system::error_code& error, size_t bytes_transferred, MsgBuffer* buffer)
{
	if(error)
	{
		LOG_DEBUG(" Error!!");
	}
	if(buffer)
	{
		delete buffer;
		buffer = NULL;
	}
}